#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
 
#define DEFAULT_PORT 5555
// default TCP socket type
#define DEFAULT_PROTO SOCK_STREAM

int main(int argc, char **argv)
{
    //char Buffer[128];
    char* Buffer = "CAL_START";
	char *ip_address= "127.0.0.1";
    unsigned short port=DEFAULT_PORT;
    int socket_type = DEFAULT_PROTO;
    WSADATA wsaData;
    
    int iResult = 0;            // used to return function results

    // the listening socket to be created
    SOCKET connect_socket = INVALID_SOCKET;

    // The socket address to be passed to bind
    sockaddr_in service;

    //----------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        wprintf(L"Error at WSAStartup()\n");
        return 1;
    }
    //----------------------
    // Create a SOCKET for listening for 
    // incoming connection requests
    connect_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (connect_socket == INVALID_SOCKET) {
        wprintf(L"socket function failed with error: %u\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }
    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port for the socket that is being bound.
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = inet_addr("127.0.0.1");
    service.sin_port = htons(DEFAULT_PORT);

	//Connect
    iResult = connect( connect_socket, (SOCKADDR*) &service, sizeof(service) );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"connect failed with error: %d\n", WSAGetLastError() );
        closesocket(connect_socket);
        WSACleanup();
        return 1;
    }

	char *sendbuf = "CAL_START";
	// Send command to GazeTracker
    iResult = send( connect_socket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        wprintf(L"send failed with error: %d\n", WSAGetLastError());
        closesocket(connect_socket);
        WSACleanup();
        return 1;
    }

    // shutdown the connection since no more data will be sent
    iResult = shutdown(connect_socket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(connect_socket);
        WSACleanup();
        return 1;
    }
    
	// close the socket
    iResult = closesocket(connect_socket);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"close failed with error: %d\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    WSACleanup();
    return 0;
}